import { nextTick } from 'vue';

const vElTableInfiniteScroll = {
    mounted(el, binding) {
        const { callback } = binding.value;
        let isLoading = false;

        const handleScroll = () => {
            const { scrollTop, scrollHeight, clientHeight } = el;
            if (scrollTop + clientHeight >= scrollHeight - 200 && !isLoading) {
                isLoading = true;
                callback().finally(() => {
                    nextTick(() => {
                        isLoading = false;
                    });
                });
            }
        };

        el.addEventListener('scroll', handleScroll);

        return () => {
            el.removeEventListener('scroll', handleScroll);
        };
    },
};

export default vElTableInfiniteScroll;